// composables/useTheme.ts

import { onMounted } from 'vue';

type Theme = 'light' | 'dark';

export const useTheme = () => {
  // 使用 Nuxt 的 useState 来创建全局共享的主题状态
  const theme = useState<Theme>('theme', () => 'light');

  const applyTheme = (newTheme: Theme) => {
    const htmlElement = document.documentElement;
    if (newTheme === 'dark') {
      htmlElement.classList.add('dark');
    } else {
      htmlElement.classList.remove('dark');
    }
    localStorage.setItem('theme', newTheme);
  };

  const toggleTheme = () => {
    const newTheme = theme.value === 'light' ? 'dark' : 'light';
    theme.value = newTheme;
    applyTheme(newTheme);
  };

  onMounted(() => {
    const savedTheme = localStorage.getItem('theme') as Theme;
    if (savedTheme) {
      theme.value = savedTheme;
    } else {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      theme.value = prefersDark ? 'dark' : 'light';
    }
    // 初始化时应用主题
    applyTheme(theme.value);
  });

  return {
    theme,
    toggleTheme,
  };
};